﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomerService
{
    public partial class OrderDetailTab : System.Web.UI.UserControl
    {
        protected SalesManagerEntities _context;
        protected tblOrderHeader _orderHeader = _emptyOrder;
        private static tblOrderHeader _emptyOrder = new tblOrderHeader();
        private Control _parentUpdatePanel;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                // Load the values from the listview back into the entity context
                for (int i = 0; i < ListView1.Items.Count; i++)
                {
                    int key = (int)ListView1.DataKeys[i].Value;
                    tblOrderDetail orderDetail = _context.tblOrderDetail.Find(new object[] { key });
                    if (orderDetail != null)
                    {
                        int qty;
                        if (int.TryParse(((TextBox)ListView1.Items[i].FindControl("txtItemQty")).Text, out qty))
                            orderDetail.Qty = qty;
                        orderDetail.DisplayDiscount = ((TextBox)ListView1.Items[i].FindControl("txtDiscount")).Text;
                    }
                }
                DateTime dt;
                if (DateTime.TryParse(txtProjShipDate.Text, out dt))
                    if (_orderHeader.ProjShipDate.Date != dt.Date)
                        _orderHeader.ProjShipDate = dt;
                decimal shipping;
                if (decimal.TryParse(txtShipping.Text, 
                    System.Globalization.NumberStyles.AllowCurrencySymbol | System.Globalization.NumberStyles.AllowDecimalPoint,
                    System.Globalization.CultureInfo.CurrentCulture,
                    out shipping))
                    _orderHeader.Shipping = shipping;
            }
            else
            {
                if (_context == null)
                    _context = (SalesManagerEntities)Session["sme"];
                ddCancelReason.DataSource = (from c in _context.codeCanceledReasons where c.Active select c).ToArray();
                ddCancelReason.DataTextField = "Description";
                ddCancelReason.DataValueField = "CanceledReasonID";
                ddCancelReason.DataBind();
            }
        }

        public new void Load(SalesManagerEntities context, tblOrderHeader orderHeader, bool forceUpdate, Control parentUpdatePanel)
        {
            _context = context;
            _orderHeader = orderHeader;
            _parentUpdatePanel = parentUpdatePanel;
            hdnOrderID.Value = _orderHeader.OrderID.ToString();
            btnCancelOrder.Disabled = !_orderHeader.CanCancel;
            btnAddItem.Disabled = !_orderHeader.CanEdit;

            if (!IsPostBack || forceUpdate)
            {
                txtProjShipDate.Text = orderHeader.ProjShipDate.ToShortDateString();
                txtProjShipDate.Enabled = orderHeader.CanEdit;
                txtShipping.Text = orderHeader.Shipping.ToString("C");
                txtShipping.Enabled = orderHeader.CanEdit;
            }
            if (!IsPostBack || forceUpdate || (Request.Params["__EVENTARGUMENT"] == "UpdateDetails"))
            {
                ListView1.DataSource = _context.tblOrderDetail.Local.Where(t => t.OrderHeader == _orderHeader);
                ListView1.DataBind();
            }
        }

        protected string GetOrderID()
        {
            return _orderHeader.OrderID.ToString();
        }

        protected void btnRemove_Click(object sender, CommandEventArgs e)
        {
            int key = int.Parse(e.CommandArgument.ToString());
            
            _context.tblOrderDetail.Remove(_context.tblOrderDetail.Find(new object[] {key}));
            //_context.SaveChanges();
            ListView1.DataSource = _context.tblOrderDetail.Local.Where(t => t.OrderHeader == _orderHeader);
            ListView1.DataBind();
        }

        protected Control FindAncestor(string name)
        {
            Control parent = this.Parent;
            while (parent != null)
            {
                if (parent.ID == name)
                    return parent;
                parent = parent.Parent;
            }
            return null;
        }

        protected void btnCancelOK_Click(object sender, EventArgs e)
        {
            _context.spCancelOrder(_orderHeader.OrderID, int.Parse(ddCancelReason.SelectedValue));

            // Refresh the OrderHeader from the database
            _context.Entry<tblOrderHeader>(_orderHeader).Reload();
            _orderHeader.InventoryTransactions.ToArray();
            _orderHeader.Transactions.ToArray();

            // Hide the cancel dialog box
            mpeCancel.Hide();

            // Trigger the OrderDetail panel to refresh.            
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "PostBack",
                    "<script  language='javascript' type='text/javascript'>" +
                    "__doPostBack('" + _parentUpdatePanel.UniqueID + "', 'UpdateDetails');" +
                    "</script>", false
                    );

        }

    }
}